package top.superflow.version.db.data

import top.superflow.db.api.DBField
import top.superflow.exception.RequestUnsupportedException
import top.superflow.log.Loggable
import top.superflow.verify.Ensure
import top.superflow.version.db.FieldVersion

class DBFieldVersion (originalField : Any) extends FieldVersion  with Ensure with Loggable{
  
  notNull(originalField, "The originalField should not be nul.")
  
  originalField match {
    case field : DBField => {
      setEntityName(field)
      
      setFieldProperties(field)
    }

    case _ => {
      throw new RequestUnsupportedException("Only DBField is supported.")
    }
  }
  
  def setEntityName(field: DBField) = {
    this.name.compareAndSet(this.name.get, field.name)
  }
  
  def setFieldProperties(field: DBField) = {
    for(getter <- DBField.getAllGetterForCriticalProperty){
      val generalFieldPropName = DBFieldPropertyVersion.getPublicName(getter.name.toString())
       
      val fieldProperty = new DBFieldPropertyVersion(generalFieldPropName, 
           DBFieldPropertyVersion.get(getter, field)) 
      try{
        this.properties += (generalFieldPropName -> fieldProperty)
      }catch {
        case t: RequestUnsupportedException => logger.warn("Found unsupported field: " + t.getMessage) // TODO: handle error
      }
    }
  }
}